//
//  SecurityTaskPanel.swift
//  SBSafetyApp
//
//  Created by Lina on 2023/5/19.
//

import Foundation
import UIKit
import RxSwift

protocol SecurityTaskPanelDelegate: AnyObject {
    func handleTaskSelected(_ model: BaglRwwcqkModel)
}

class SecurityTaskPanel: UIView {
    weak var delegate: SecurityTaskPanelDelegate?
    var disposeBag = DisposeBag()

    lazy var titleView: SectionTitleView = {
        let view = SectionTitleView(withStyle: SectionTitleStyleEnum.Style2, title: "各任务完成情况")
        return view
    }()

    lazy var taskView: UIStackView = {
        let view = UIStackView()
        view.axis = .vertical
        view.distribution = .equalSpacing
        return view
    }()

    init() {
        super.init(frame: .zero)
        backgroundColor = UIColor.white
        setupUI()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func buildWDList(_ modals: [BaglRwwcqkModel?]) {
        taskView.removeAllSubViews()
        
        for (index, modal) in modals.enumerated() {
            if let m = modal {
                let view = TaskListCellView()
                view.rx.tapGesture().when(.recognized)
                    .subscribe(onNext: { _ in
                        self.delegate?.handleTaskSelected(m)
                    })
                    .disposed(by: disposeBag)
                            
                view.buildModels(data: m)
                taskView.addArrangedSubview(view)
                view.snp.makeConstraints { make in
                    make.height.equalTo(70)
                }
                if index == modals.count - 1 {
                    view.line.isHidden = true
                }
            }
        }
    }

    func setupUI() {
        layer.cornerRadius = 8
        layer.masksToBounds = true
        backgroundColor = .white

        addSubview(titleView)
        titleView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.top.equalToSuperview().offset(20)
            make.height.equalTo(18)
        }

        addSubview(taskView)
        taskView.snp.makeConstraints { make in
            make.top.equalTo(titleView.snp.bottom).offset(12)
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview()
        }
    }
}
